#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mqueue.h>

#define QUEUE_NAME "/my_queue"
#define MAX_MSG_SIZE 1280
#define MAX_MSG_NUM 10

int main()
{
    mqd_t mq;
    struct mq_attr attr;
    char buffer[MAX_MSG_SIZE + 1];
    int msg_count = 0;

    // 初始化队列属性
    attr.mq_flags = 0;
    attr.mq_maxmsg = MAX_MSG_NUM;
    attr.mq_msgsize = MAX_MSG_SIZE;
    attr.mq_curmsgs = 0;

    // 打开或创建消息队列
    mq = mq_open(QUEUE_NAME, O_CREAT | O_RDWR, 0666, &attr);
    if (mq == (mqd_t)-1) {
        perror("mq_open");
        exit(1);
    }

    // 发送消息
    sprintf(buffer, "Hello, this is message %d", ++msg_count);
    if (mq_send(mq, buffer, strlen(buffer) + 1, 0) == -1) {
        perror("mq_send");
        exit(1);
    }

    // 接收消息
    if (mq_receive(mq, buffer, MAX_MSG_SIZE, NULL) == -1) {
        perror("mq_receive");
        exit(1);
    }
    printf("Received message: %s\n", buffer);

    // 关闭并删除消息队列
    mq_close(mq);
    mq_unlink(QUEUE_NAME);

    return 0;
}